﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using System.Web.Security;
using Experts.UI.Utils;
using System.Security.Cryptography;
using System.Text;
using System.Xml;

namespace Experts.UI.Controllers
{
    public class WeChatController : Controller
    {
        public const string TOKEN = "gtzdh";
        private static string accessToken = "";
        private static int expireTime = 0;

        public static string AccessToken
        {
            get
            {
                //获取微信配置
                XmlDocument Xml = new XmlDocument();
                Xml.Load(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/WeiXin.config"));
                string appid = Xml.SelectSingleNode("weixin/appid").InnerText;
                string appsecret = Xml.SelectSingleNode("weixin/appsecret").InnerText;
                //如果已经存在accessToken并且没有过期
                int currentTimeMillis = TimeStampUtils.ConvertDateTimeInt(DateTime.Now);

                if (accessToken == "" || currentTimeMillis > expireTime)
                {
                    string url = "https://api.weixin.qq.com/cgi-bin/token";
                    string param = string.Format("grant_type=client_credential&appid={0}&secret={1}", appid, appsecret);
                    string jsonStr = HttpUtils.HttpGet(url, param);
                    //处理错误
                    if (jsonStr.IndexOf("access_token") == -1)
                    {
                        accessToken = "";
                    }
                    else
                    {
                        AccessTokenResult result = JsonConvert.DeserializeObject<AccessTokenResult>(jsonStr);
                        accessToken = result.access_token;
                        expireTime = currentTimeMillis + result.expires_in - 200;
                    }
                    return accessToken;
                }
                return accessToken;
            }
        }
        // GET: WeChat
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult Index(string signature, string timestamp, string nonce, string echostr)
        {
            if (checkSignature(signature, timestamp, nonce))
            {
                return Content(echostr);
            }
            return Content("接入失败");
        }

        private bool checkSignature(string signature, string timestamp, string nonce)
        {
            string[] strArr = { TOKEN, timestamp, nonce };
            Array.Sort(strArr);  //字典排序
            string tempStr = string.Join("", strArr);
            //string resultStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tempStr, "SHA1");
            string resultStr = HttpUtils.SHA1Hash(tempStr);
            if (resultStr.ToLower() == signature)
            {
                return true;
            }
            return false;
        }

        class AccessTokenResult
        {
            public string access_token { get; set; }
            public int expires_in { get; set; }
        }
    }
}